{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import torch\n",
    "from tqdm.auto import tqdm\n",
    "\n",
    "import ddpm\n",
    "import datasets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### forward"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_timesteps = 50\n",
    "plot_step = 5\n",
    "\n",
    "num_plots = math.ceil(num_timesteps / plot_step)\n",
    "num_cols = 5\n",
    "num_rows = math.ceil(num_plots / num_cols)\n",
    "\n",
    "fig = plt.figure(figsize=(15, 6))\n",
    "\n",
    "noise_scheduler = ddpm.NoiseScheduler(num_timesteps=num_timesteps)\n",
    "dataset = datasets.get_dataset(\"dino\", n=1000)\n",
    "x0 = dataset.tensors[0]\n",
    "\n",
    "plt_cnt = 1\n",
    "plt.subplot(num_rows, num_cols, plt_cnt)\n",
    "plt.scatter(x0[:, 0], x0[:, 1], alpha=0.5, s=15)\n",
    "plt.title(\"data\")\n",
    "plt.xlim(-3.5, 3.5)\n",
    "plt.ylim(-4., 4.75)\n",
    "plt.axis(\"off\")\n",
    "        \n",
    "for t in range(len(noise_scheduler)):\n",
    "    timesteps = np.repeat(t, len(x0))\n",
    "    noise = torch.randn_like(x0)\n",
    "    sample = noise_scheduler.add_noise(x0, noise, timesteps)\n",
    "    if (t + 1) % plot_step == 0 and (t + 1) != len(noise_scheduler):\n",
    "        plt_cnt += 1\n",
    "        plt.subplot(num_rows, num_cols, plt_cnt)\n",
    "        plt.scatter(sample[:, 0], sample[:, 1], alpha=0.5, s=15)\n",
    "        plt.title(f\"step: {t + 1}\")\n",
    "        plt.xlim(-3.5, 3.5)\n",
    "        plt.ylim(-4., 4.75)\n",
    "        plt.axis(\"off\")\n",
    "        \n",
    "fig.tight_layout()\n",
    "plt.savefig(\"static/forward.png\", facecolor=\"white\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### reverse"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!python ddpm.py --experiment_name dino_base"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = ddpm.MLP()\n",
    "\n",
    "path = \"exps/dino_base/model.pth\"\n",
    "model.load_state_dict(torch.load(path))\n",
    "model.eval()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "eval_batch_size = 1000\n",
    "num_timesteps = 50\n",
    "plot_step = 5\n",
    "noise_scheduler = ddpm.NoiseScheduler(num_timesteps=num_timesteps)\n",
    "sample = torch.randn(eval_batch_size, 2)\n",
    "timesteps = list(range(num_timesteps))[::-1]\n",
    "samples = []\n",
    "steps = []\n",
    "for i, t in enumerate(tqdm(timesteps)):\n",
    "    t = torch.from_numpy(np.repeat(t, eval_batch_size)).long()\n",
    "    with torch.no_grad():\n",
    "        residual = model(sample, t)\n",
    "    sample = noise_scheduler.step(residual, t[0], sample)\n",
    "    if (i + 1) % plot_step == 0:\n",
    "        samples.append(sample.numpy())\n",
    "        steps.append(i + 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_cols = 5\n",
    "num_rows = math.ceil(len(samples) / num_cols)\n",
    "fig = plt.figure(figsize=(15, 6))\n",
    "for i, sample in enumerate(samples):\n",
    "    plt.subplot(num_rows, num_cols, i + 1)\n",
    "    plt.scatter(sample[:, 0], sample[:, 1], alpha=0.5, s=15)\n",
    "    plt.title(f\"step: {steps[i]}\")\n",
    "    plt.xlim(-3.5, 3.5)\n",
    "    plt.ylim(-4., 4.75)\n",
    "    plt.axis(\"off\")\n",
    "fig.tight_layout()\n",
    "plt.savefig(\"static/reverse.png\", facecolor=\"white\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## ablations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_ablation(frames_dict, outname):\n",
    "    num_rows = len(frames_dict)\n",
    "    num_cols = 10\n",
    "\n",
    "    fig = plt.figure(figsize=(3.5*num_cols, 3*num_rows + 0.5))\n",
    "    row = 0\n",
    "\n",
    "    for name, frames in frames_dict.items():\n",
    "        epoch_step = len(frames) // num_cols\n",
    "        offset = row*(num_cols + 1)\n",
    "        plt.subplot(num_rows, num_cols + 1, offset + 1)\n",
    "        plt.scatter(0, 0, alpha=0)\n",
    "        plt.text(0, 0, name, fontdict={\"size\": 30})\n",
    "        plt.xlim(-0.25, 2)\n",
    "        plt.axis(\"off\")\n",
    "\n",
    "        for i in range(num_cols):\n",
    "            plt.subplot(num_rows, num_cols + 1, offset + i + 2)\n",
    "            ix = i * epoch_step\n",
    "            frame = frames[ix]\n",
    "            plt.scatter(frame[:, 0], frame[:, 1], s=5, alpha=0.7)\n",
    "            if row == 0:\n",
    "                if i == 0:\n",
    "                    title = f\"epoch {ix}\"\n",
    "                else:\n",
    "                    title = f\"{ix}\"\n",
    "                plt.title(title, fontdict={\"size\": 30}, pad=30)\n",
    "            plt.xlim(-3.5, 3.5)\n",
    "            plt.ylim(-4., 4.75)\n",
    "            plt.axis(\"off\")\n",
    "\n",
    "        row += 1\n",
    "\n",
    "    plt.tight_layout()\n",
    "    plt.savefig(outname, facecolor=\"white\")\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!python ddpm.py --dataset moons --experiment_name moons_base\n",
    "!python ddpm.py --dataset dino --experiment_name dino_base\n",
    "!python ddpm.py --dataset line --experiment_name line_base\n",
    "!python ddpm.py --dataset circle --experiment_name circle_base"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "frames_dict = {\n",
    "    \"moons\": np.load(\"exps/moons_base/frames.npy\"),\n",
    "    \"dino\": np.load(\"exps/dino_base/frames.npy\"),\n",
    "    \"line\": np.load(\"exps/line_base/frames.npy\"),\n",
    "    \"circle\": np.load(\"exps/circle_base/frames.npy\"),\n",
    "}\n",
    "\n",
    "plot_ablation(frames_dict, \"static/datasets.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### learning rate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!python ddpm.py --learning_rate 1e-2 --experiment_name dino_lr1e-2\n",
    "!python ddpm.py --learning_rate 1e-3 --experiment_name dino_lr1e-3\n",
    "!python ddpm.py --learning_rate 1e-4 --experiment_name dino_lr1e-4\n",
    "!python ddpm.py --learning_rate 1e-5 --experiment_name dino_lr1e-5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "frames_dict = {\n",
    "    \"lr 1e-2\": np.load(\"exps/dino_lr1e-2/frames.npy\"),\n",
    "    \"lr 1e-3\": np.load(\"exps/dino_lr1e-3/frames.npy\"),\n",
    "    \"lr 1e-4\": np.load(\"exps/dino_lr1e-4/frames.npy\"),\n",
    "    \"lr 1e-5\": np.load(\"exps/dino_lr1e-5/frames.npy\"),\n",
    "}\n",
    "\n",
    "plot_ablation(frames_dict, \"static/learning_rate.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### num_timesteps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!python ddpm.py --num_timesteps 5 --experiment_name dino_timesteps5\n",
    "!python ddpm.py --num_timesteps 10 --experiment_name dino_timesteps10\n",
    "!python ddpm.py --num_timesteps 25 --experiment_name dino_timesteps25\n",
    "!python ddpm.py --num_timesteps 50 --experiment_name dino_timesteps50\n",
    "!python ddpm.py --num_timesteps 100 --experiment_name dino_timesteps100\n",
    "!python ddpm.py --num_timesteps 250 --experiment_name dino_timesteps250"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "frames_dict = {\n",
    "    \"        5\": np.load(\"exps/dino_timesteps5/frames.npy\"),\n",
    "    \"       10\": np.load(\"exps/dino_timesteps10/frames.npy\"),\n",
    "    \"       25\": np.load(\"exps/dino_timesteps25/frames.npy\"),\n",
    "    \"       50\": np.load(\"exps/dino_timesteps50/frames.npy\"),\n",
    "    \"      100\": np.load(\"exps/dino_timesteps100/frames.npy\"),\n",
    "    \"      250\": np.load(\"exps/dino_timesteps250/frames.npy\"),\n",
    "}\n",
    "\n",
    "plot_ablation(frames_dict, \"static/num_timesteps.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### beta schedule"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!python ddpm.py --beta_schedule quadratic --experiment_name dino_quadratic_schedule"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "frames_dict = {\n",
    "    \"linear\": np.load(\"exps/dino_base/frames.npy\"),\n",
    "    \"quadratic\": np.load(\"exps/dino_quadratic_schedule/frames.npy\"),\n",
    "}\n",
    "\n",
    "plot_ablation(frames_dict, \"static/beta_schedule.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### hidden size"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!python ddpm.py --hidden_size 16 --experiment_name dino_hid_size_16\n",
    "!python ddpm.py --hidden_size 32 --experiment_name dino_hid_size_32\n",
    "!python ddpm.py --hidden_size 64 --experiment_name dino_hid_size_64\n",
    "!python ddpm.py --hidden_size 256 --experiment_name dino_hid_size_256\n",
    "!python ddpm.py --hidden_size 512 --experiment_name dino_hid_size_512"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "frames_dict = {\n",
    "    \"       16\": np.load(\"exps/dino_hid_size_16/frames.npy\"),\n",
    "    \"       32\": np.load(\"exps/dino_hid_size_32/frames.npy\"),\n",
    "    \"       64\": np.load(\"exps/dino_hid_size_64/frames.npy\"),\n",
    "    \"      128\": np.load(\"exps/dino_base/frames.npy\"),\n",
    "    \"      256\": np.load(\"exps/dino_hid_size_256/frames.npy\"),\n",
    "    \"      512\": np.load(\"exps/dino_hid_size_512/frames.npy\"),\n",
    "}\n",
    "\n",
    "plot_ablation(frames_dict, \"static/hidden_size.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### num layers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!python ddpm.py --hidden_layers 1 --experiment_name dino_hid_layers_1\n",
    "!python ddpm.py --hidden_layers 2 --experiment_name dino_hid_layers_2\n",
    "!python ddpm.py --hidden_layers 4 --experiment_name dino_hid_layers_4\n",
    "!python ddpm.py --hidden_layers 5 --experiment_name dino_hid_layers_5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "frames_dict = {\n",
    "    \"        1\": np.load(\"exps/dino_hid_layers_1/frames.npy\"),\n",
    "    \"        2\": np.load(\"exps/dino_hid_layers_2/frames.npy\"),\n",
    "    \"        3\": np.load(\"exps/dino_base/frames.npy\"),\n",
    "    \"        4\": np.load(\"exps/dino_hid_layers_4/frames.npy\"),\n",
    "    \"        5\": np.load(\"exps/dino_hid_layers_5/frames.npy\"),\n",
    "    \n",
    "}\n",
    "\n",
    "plot_ablation(frames_dict, \"static/num_hidden_layers.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### positional embedding (timestep)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!python ddpm.py --time_embedding learnable --experiment_name dino_time_emb_learnable\n",
    "!python ddpm.py --time_embedding linear --experiment_name dino_time_emb_linear\n",
    "!python ddpm.py --time_embedding zero --experiment_name dino_time_emb_zeros"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "frames_dict = {\n",
    "    \"learnable\": np.load(\"exps/dino_time_emb_learnable/frames.npy\"),\n",
    "    \"sinusoidal\": np.load(\"exps/dino_base/frames.npy\"),\n",
    "    \"linear\": np.load(\"exps/dino_time_emb_linear/frames.npy\"),\n",
    "    \"zero\": np.load(\"exps/dino_time_emb_zeros/frames.npy\"),\n",
    "}\n",
    "\n",
    "plot_ablation(frames_dict, \"static/time_embedding.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### positional embedding (inputs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!python ddpm.py --input_embedding learnable --experiment_name dino_input_emb_learnable\n",
    "!python ddpm.py --input_embedding linear --experiment_name dino_input_emb_linear\n",
    "!python ddpm.py --input_embedding identity --experiment_name dino_input_emb_identity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "frames_dict = {\n",
    "    \"learnable\": np.load(\"exps/dino_input_emb_learnable/frames.npy\"),\n",
    "    \"sinusoidal\": np.load(\"exps/dino_base/frames.npy\"),\n",
    "    \"linear\": np.load(\"exps/dino_input_emb_linear/frames.npy\"),\n",
    "    \"identity\": np.load(\"exps/dino_input_emb_identity/frames.npy\"),\n",
    "}\n",
    "\n",
    "plot_ablation(frames_dict, \"static/input_embedding.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### forward and reverse process animation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from celluloid import Camera"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_timesteps = 250\n",
    "noise_scheduler = ddpm.NoiseScheduler(num_timesteps=num_timesteps)\n",
    "\n",
    "model = ddpm.MLP()\n",
    "path = \"exps/dino_timesteps250/model.pth\"\n",
    "model.load_state_dict(torch.load(path))\n",
    "model.eval()\n",
    "\n",
    "dataset = datasets.get_dataset(\"dino\", n=1000)\n",
    "x0 = dataset.tensors[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "forward_samples = []\n",
    "forward_samples.append(x0)\n",
    "for t in range(len(noise_scheduler)):\n",
    "    timesteps = np.repeat(t, len(x0))\n",
    "    noise = torch.randn_like(x0)\n",
    "    sample = noise_scheduler.add_noise(x0, noise, timesteps)\n",
    "    forward_samples.append(sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "eval_batch_size = len(dataset)\n",
    "sample = torch.randn(eval_batch_size, 2)\n",
    "timesteps = list(range(num_timesteps))[::-1]\n",
    "reverse_samples = []\n",
    "reverse_samples.append(sample.numpy())\n",
    "for i, t in enumerate(tqdm(timesteps)):\n",
    "    t = torch.from_numpy(np.repeat(t, eval_batch_size)).long()\n",
    "    with torch.no_grad():\n",
    "        residual = model(sample, t)\n",
    "    sample = noise_scheduler.step(residual, t[0], sample)\n",
    "    reverse_samples.append(sample.numpy())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "xmin, xmax = -3.5, 3.5\n",
    "ymin, ymax = -4., 4.75\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "camera = Camera(fig)\n",
    "\n",
    "# forward\n",
    "for i, sample in enumerate(forward_samples):\n",
    "    plt.scatter(sample[:, 0], sample[:, 1], alpha=0.5, s=15, color=\"blue\")\n",
    "    ax.text(0.0, 0.95, f\"step {i: 4} / {num_timesteps}\", transform=ax.transAxes)\n",
    "    ax.text(0.0, 1.01, \"Forward process\", transform=ax.transAxes, size=15)\n",
    "    plt.xlim(xmin, xmax)\n",
    "    plt.ylim(ymin, ymax)\n",
    "    plt.axis(\"off\")\n",
    "    camera.snap()\n",
    "        \n",
    "# reverse\n",
    "for i, sample in enumerate(reverse_samples):\n",
    "    plt.scatter(sample[:, 0], sample[:, 1], alpha=0.5, s=15, color=\"blue\")\n",
    "    ax.text(0.0, 0.95, f\"step {i: 4} / {num_timesteps}\", transform=ax.transAxes)\n",
    "    ax.text(0.0, 1.01, \"Reverse process\", transform=ax.transAxes, size=15)\n",
    "    plt.xlim(xmin, xmax)\n",
    "    plt.ylim(ymin, ymax)\n",
    "    plt.axis(\"off\")\n",
    "    camera.snap()\n",
    "    \n",
    "animation = camera.animate(blit=True, interval=35)\n",
    "animation.save(\"static/animation.mp4\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
